package com.ls.controller;


import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ls.entity.Dict;
import com.ls.entity.ResResult;
import com.ls.service.Dictervice;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import static com.ls.entity.ResResult.success;

/**
 * <p>
 * 组织架构表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-05-09
 */
@Controller
public class DictController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private  ObjectMapper json = new ObjectMapper();

    @Autowired
    private Dictervice dictService;

    /*
      1、首先查询缓存，如果存在，直接取出json字符串，反序列化
      2、不存在查询数据库
     */
    @GetMapping("dict/list")
    @ResponseBody
    public ResResult list() throws Exception {
        String cusJson = stringRedisTemplate.opsForValue().get("cache:dict");
        List<Dict> dictList = null;
        if(null==cusJson || "".equals(cusJson)){
            dictList = dictService.list(null);
            String mapJson = json.writeValueAsString(dictList);
            //写入缓存
            stringRedisTemplate.opsForValue().set("cache:dict",mapJson);
        }else {//存在,读缓存
            dictList = json.readValue(cusJson,List.class);
        }
        return  success(dictList);
    }

    @RequestMapping("dictList")
    public String list1(){
        return "dict/dictList";
    }


    @DeleteMapping("/dict/{id}")
    @ResponseBody
    public ResResult del(@PathVariable Integer id){
        boolean del = dictService.removeById ( id );
        if (del){
            return success ("删除成功");
        }
        return ResResult.error ("删除失败");
    }

    @GetMapping("/dict/updateUI")
    public String dictUpdate(Integer did, Model model) {
        List<Dict> list = dictService.list(null);
        model.addAttribute("dictList",list);
        Dict dict = dictService.getById(did);
        model.addAttribute("dict",dict);
        return "dict/dictUpdate";
    }

    @PutMapping("/dict")
    @ResponseBody
    public ResResult update(Dict dict){
        boolean update = dictService.updateById ( dict );
        if (update){
            return success ("修改成功");
        }
        return ResResult.error ("修改失败");
    }

    @GetMapping("/dict/addUI")
    public String dictAdd(Model model) {
        List<Dict> list = dictService.list(null);
        model.addAttribute("dictList",list);
        return "dict/dictAdd";
    }

    @PostMapping("/dict")
    @ResponseBody
    public ResResult save(Dict dict){
        boolean save = dictService.save(dict);
        if (save){
            return success();
        }
        return ResResult.error();
    }


    @ApiOperation(value = "导出数据字典接⼝")
    @GetMapping("dict/exportData")
    public void export(HttpServletResponse response){
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            List<Dict> dictList = dictService.list(null);
            EasyExcel.write(response.getOutputStream(), Dict.class).sheet("数据字典").doWrite(dictList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    //将数据导入到数据库
    @PostMapping("dict/importData")
    public ResResult importData(MultipartFile file) throws IOException {
        dictService.importData(file);
        return ResResult.success ();
    }
}

